from pydantic import BaseModel, root_validator
from pydantic.fields import Field
from utils import random_ua
from utils import get_function_from_path_string
from config import settings


class RequestItem(BaseModel):
    url: str
    method: str = 'GET'
    params: dict = None
    content: bytes = None
    data: dict = None
    files: dict = None
    json_data: dict = Field(None, alias='json')
    headers: dict = None
    cookies: dict = None
    timeout: float = 10.0
    follow_redirects: bool = False

    proxies: bool | str = None
    http2: bool = False

    meta: dict = None

    parse_callback: str = settings.undefined
    data_callback: str = settings.undefined

    @root_validator
    def check_headers(cls, values):
        parse_callback = values.get("parse_callback")
        if parse_callback != settings.undefined and not get_function_from_path_string(parse_callback):
            raise ValueError(f"parse_callback:[{parse_callback}]没有找到~!")

        data_callback = values.get("data_callback")
        if data_callback != settings.undefined and not get_function_from_path_string(data_callback):
            raise ValueError(f"data_callback:[{data_callback}]没有找到~!")

        headers = values.get('headers')
        if headers is None:
            values["headers"] = {'user-agent': random_ua()}
        elif headers.get('user-agent') or headers.get('User-Agent'):
            ...
        else:
            values["headers"]['user-agent'] = random_ua()
        return values

    def json(self, *args, **kwargs):
        super_json = super(RequestItem, self).json(*args, **kwargs)
        super_json = super_json.replace('"json_data":', '"json":')
        return super_json

    def dict(self, *args, **kwargs):
        super_dict = super(RequestItem, self).dict(*args, **kwargs)

        json_data = super_dict.pop('json_data', None)
        super_dict['json'] = json_data
        return super_dict


if __name__ == '__main__':
    print(RequestItem(url="http://123", method="get", json={"a": "b"}, callback="parse").json())
